package com.study.springbootsecurity.config;

import com.study.springbootsecurity.exception.BusinessException;
import com.study.springbootsecurity.exception.ExceptionConstant;
import com.study.springbootsecurity.util.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.MessageSourceResolvable;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.stream.Collectors;

/**
 * @Description: TODO
 * @author: Huangjianyun
 * @date: 2025-06-03 19:06
 */
@ControllerAdvice
public class ExceptionAdvice {
    public static Logger logger = LoggerFactory.getLogger(ExceptionAdvice.class);


    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    public Result doBusinessException(Exception e) {
        logger.error("业务异常消息：", e.getMessage());
        return Result.fail(-1,BusinessException.create(e.getMessage()).getMessage());
    }


    /**
     * 处理请求参数格式错误 @RequestBody上使用@Valid 实体上使用@NotNull等，验证失败后抛出的异常是MethodArgumentNotValidException异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public Result MethodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        String message = e.getBindingResult().getAllErrors().stream().map(MessageSourceResolvable::getDefaultMessage).collect(Collectors.joining());
        return Result.fail(ExceptionConstant.PARAM_ERROR.getCode(), message);
    }

    /**
     * 处理Get请求中 使用@Valid 验证路径中请求实体校验失败后抛出的异常
     */
    @ExceptionHandler(BindException.class)
    @ResponseBody
    public Result BindExceptionHandler(BindException e) {
        String message = e.getBindingResult().getAllErrors().stream().map(MessageSourceResolvable::getDefaultMessage).collect(Collectors.joining());
        return Result.fail(ExceptionConstant.PARAM_ERROR.getCode(), message);
    }

    // 通用异常处理（必须放在最后）
//    @ExceptionHandler(Exception.class)
//    @ResponseBody
//    public Result exceptionHandler(Exception e) {
//        logger.error("未处理的异常", e);
//        return Result.fail(-1,
//                "系统异常：" + e.getMessage());
//    }

}
